package com.itheima.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception.UserException;
import com.itheima.service.UserService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;


    @RequestMapping("/getUserName")
    public Result getUserName(){
        //从spring security上下文中获取用户名
        User user = null;//这个返回的就是我们在SpringSecurityUserService里面给框架的User对象
        try {
            user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return Result.success("未登录");
        }

        return Result.success("",user.getUsername());
    }


    /**分页
     */
    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.findPage(queryPageBean);
    }


    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user){
        userService.add(user);
        return Result.success("");
    }


    @RequestMapping("deletebyid")
    public Result deletebyid(Integer id){
        try {
            userService.deletebyid(id);
            return Result.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("");
        }
    }


    @RequestMapping("findbyid4updata")
    public Result findbyid4updata(Integer id){
        try {
            Map map= userService.findbyid4updata(id);
            return Result.success("",map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("");
        }
    }


    @RequestMapping("edit")
    public Result edit(@RequestBody com.itheima.pojo.User user){
        try {
            userService.edit(user);
            return Result.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("");
        }
    }






}
